import logging
import traceback

from flask import jsonify
from dao.db_connect import db_connect as db
from controller.carbon_alipay.carbon_alipay_controller import AliPay
import controller.carbon_alipay.AlipayConfig as AlipayConfig

success = 200  # 请求成功
# errors
internal_error = 500  # 服务器错误
identification_error = 100  # 未识别成功
order_not_exists = 101  # 订单不存在
data_missing = 102  # 订单不存在
file_not_vip = 103  # 文件不是付费文件
file_purchased = 104  # 文件已经购买


class GetTradeInfo(object):
    def __init__(self):
        print("GetFilesUrl init")

    @classmethod
    def get_vips(cls, request):
        """
        获取VIP购买信息
        """
        logging.debug("working on get_vips")
        msg = "获取列表成功"
        code = success

        label = request.values.get('label')
        data = []
        if label is None or len(label) == 0:
            label = 'vip'

        try:
            query_sql = f'select good_id, good_name, good_describe, good_price, original_price from goods ' \
                        f'where good_label = "{label}" order by good_id'
            data = db.queryAll(query_sql)
            for good in data:
                good['good_price'] = float(good['good_price']) / 100
                good['original_price'] = float(good['original_price']) / 100
            print(data)

        except Exception as e:
            msg = "获取列表失败"
            code = data_missing
            logging.debug(traceback.format_exc())

        resp = {
            "code": code,
            "msg": msg,
            "data": data
        }
        return jsonify(resp)

    @classmethod
    def get_file(cls, request):
        """
        获取文件购买信息
        """
        logging.debug("working on get_file")
        msg = "获取列表成功"
        code = success
        data = []

        file_id = request.values.get('file_id')
        if file_id is None or len(file_id) == 0:
            code = identification_error
            msg = "file_id参数缺失，请修改请求！"
            return jsonify(code=code, data={}, msg=msg)

        try:
            query_sql = f'select files_info.good_id, good_name, good_describe, good_price, original_price ' \
                        f'from goods, files_info ' \
                        f'where files_info.id = "{file_id}" and files_info.good_id = goods.good_id'
            data = db.queryAll(query_sql)
            for good in data:
                good['good_price'] = float(good['good_price']) / 100
                good['original_price'] = float(good['original_price']) / 100
            print(data)

        except Exception as e:
            msg = "获取列表失败"
            code = data_missing
            logging.debug(traceback.format_exc())

        resp = {
            "code": code,
            "msg": msg,
            "data": data
        }
        return jsonify(resp)

    @classmethod
    def purchase_vip(cls, request):
        """
        购买vip
        """
        logging.debug("working on purchase_vip")
        msg = "获取链接成功！"
        code = success

        return_url = request.values.get('return_url')
        good_id = request.values.get('good_id')
        user_id = request.values.get('user_id')

        if return_url is None or len(return_url) == 0:
            return_url = AlipayConfig.return_url

        if good_id is None or len(good_id) == 0:
            code = identification_error
            msg = "good_id参数缺失，请修改请求！"
            return jsonify(code=code, data={}, msg=msg)

        if user_id is None or len(user_id) == 0:
            code = identification_error
            msg = "user_id参数缺失，请修改请求！"
            return jsonify(code=code, data={}, msg=msg)

        out_trade_no, response = AliPay.pay(return_url, good_id, user_id)
        if response is None:
            code = data_missing
            msg = "下单失败！"

        return jsonify(code=code, data=response, out_trade_no=out_trade_no, msg=msg)

    @classmethod
    def purchase_file(cls, request):
        """
        购买文件
        """
        logging.debug("working on purchase_filee")
        msg = "获取链接成功！"
        code = success

        return_url = request.values.get('return_url')
        file_id = request.values.get('file_id')
        user_id = request.values.get('user_id')

        if return_url is None or len(return_url) == 0:
            return_url = AlipayConfig.return_url

        if file_id is None or len(file_id) == 0:
            code = identification_error
            msg = "file_id参数缺失，请修改请求！"
            return jsonify(code=code, data={}, msg=msg)

        if user_id is None or len(user_id) == 0:
            code = identification_error
            msg = "user_id参数缺失，请修改请求！"
            return jsonify(code=code, data={}, msg=msg)

        # 检查是否存在该文件
        query_sql = f"select id, name, rank, good_id from files_info where id = '{file_id}'"
        file_info = db.queryOne(query_sql)
        if file_info is None:
            code = identification_error
            logging.error(f"file_info: {file_info} 文件不存在！")
            jsonify(code=code, data={}, msg="文件不存在！")

        good_id = file_info.get('good_id')
        file_rank = file_info.get('rank')
        if file_rank == 0:
            code = file_not_vip
            logging.warning(f"file_info: {file_info} 文件不是付费文件！")
            jsonify(code=code, data={}, msg="文件不是付费文件！")

        # 检查是否已经购买该文件
        query_sql = f"select uid, fid from files_purchased where uid = '{user_id}' and fid = '{file_id}'"
        purchase_info = db.queryOne(query_sql)
        if purchase_info is not None:
            code = file_purchased
            logging.warning(f"file_info: {file_info} 文件已经购买！")
            jsonify(code=code, data={}, msg="文件已经购买！")

        # 下单
        out_trade_no, response = AliPay.pay(return_url, good_id, user_id)
        if response is None:
            code = data_missing
            msg = "下单失败！"

        return jsonify(code=code, data=response, out_trade_no=out_trade_no, msg=msg)

    @classmethod
    def query(cls, request):
        """
        查询订单
        """
        logging.debug("working on trade query")
        code = success
        out_trade_no = request.values.get('out_trade_no')

        if out_trade_no is None or len(out_trade_no) == 0:
            code = identification_error
            msg = "out_trade_no参数缺失，请修改请求！"
            return jsonify(code=code, status=0, msg=msg)

        # code: 100 TRADE_SUCCESS
        #     101 TRADE_FINISHED
        #     102 WAIT_BUYER_PAY
        #     103 TRADE_CLOSED
        #     104 ACQ.TRADE_NOT_EXIST
        #     105 out_trade_no & trade_no 同时为空
        #     106 数据库订单丢失
        #     107 数据库数据异常
        #     108 其他支付宝查询异常
        #     109 订单金额不符合
        #     110 系统状态更新失败
        result = AliPay.query(out_trade_no=out_trade_no, trade_no=None)
        if result == 100 or result == 101:
            msg = "支付完成！"
            return jsonify(code=code, status=2, msg=msg)
        if result == 102:
            msg = "等待支付！"
            return jsonify(code=code, status=1, msg=msg)
        if result == 104:
            msg = "订单未生成！"
            return jsonify(code=code, status=0, msg=msg)
        if result == 103:
            msg = "订单已过期或关闭，请重新下单！"
            return jsonify(code=code, status=3, msg=msg)

        msg = "其他查询异常！"
        if result == 106:
            msg = "数据库订单丢失！"
        if result == 107:
            msg = "数据库数据异常！"
        if result == 108:
            msg = "其他支付宝查询异常！"
        if result == 109:
            msg = "订单金额不符合！"
        if result == 110:
            msg = "系统状态更新失败！"

        code = data_missing
        return jsonify(code=code, status=0, msg=msg)

    @classmethod
    def get_orders(cls, request):
        """
        用户查询已有的订单
        """
        logging.debug("working on get_orders")
        msg = "查询成功！"
        code = success
        user_id = request.values.get('user_id')
        data = []

        if user_id is None or len(user_id) == 0:
            code = identification_error
            msg = "user_id参数缺失，请修改请求！"
            return jsonify(code=code, status=0, msg=msg)

        try:
            query_sql = f'select out_trade_no, trade_no, subject, body, total_amount, ' \
                        f'DATE_FORMAT(gmt_create, "%Y-%m-%d %H:%i:%s") as gmt_create ' \
                        f'from orders where user_id="{user_id}" order by gmt_create'
            data = db.queryAll(query_sql)
        except Exception as e:
            msg = "获取列表失败"
            code = data_missing
            logging.debug(traceback.format_exc())

        resp = {
            "code": code,
            "msg": msg,
            "data": data,
        }
        return jsonify(code=code, data=resp, msg=msg)
